import sys
import os
import re
from jinja2 import Template
import subprocess
from typing import List, Dict
import json
import copy

from .Util import Util
from .DDSUtil import DDSUtil
from ..entity import AtomService, Client, Message
from .AtomServiceUtil import AtomServiceUtil
from .ClientUtil import ClientUtil


class DDSClientUtil:

    def __init__(self, client):
        pass

    @staticmethod
    def accomplishAllClient(orchestrattion_info: dict):
        """
        完成所有dds客户端的所有流程
        """
        # 确保文件夹存在，并将json保存到文件夹

        client: Client = DDSClientUtil.generateClient(orchestrattion_info)
        client_path: str = f"{os.path.dirname(os.path.abspath(__file__))}/../../../db/client/{client.get_name()}/"
        # 将orchestrattion_info保存到文件夹
        with open(client_path + f"{client.get_name()}.json", "w") as f:
            json.dump(orchestrattion_info, f, indent=4)
        # 生成通信模块代码
        Util.generateHeaderHppAndCpp(client_path + "sync_client/")

        ClientUtil.generateSyncClientCMakeLists(client)
        ClientUtil.compileSyncClient(client)
        ClientUtil.generateExecShell(client._name)

    @staticmethod
    def generateClient(orchestrattion_info: dict):
        """
        解析并编译开始和结束节点中的结构体为idl文件
        """
        DDSUtil.compileStructs(orchestrattion_info)
        # 头文件需要引入的idl名称列表
        idl_list: List[str] = list()

        # 获取使用到的service的名称列表（不重复）,获取service的dict列表（可以重复）
        service_name_list: List[str] = list()
        for node in orchestrattion_info.get("nodes", []):
            if (
                node.get("type", "") == "SERVICE"
                and node.get("name", "") not in service_name_list
            ):
                service_name_list.append(node.get("name", ""))
        # 为orchestrattion_info的node添加服务的具体信息，即添加一个service_info属性
        for node in orchestrattion_info.get("nodes", []):
            if node.get("type", "") == "SERVICE":
                node["service_info"] = AtomServiceUtil.getAtomServiceJson(
                    node.get("name", "")
                )
            if node.get("type", "") == "START" or node.get("type", "") == "END":
                node["message_info"] = DDSClientUtil._getIdlJson(
                    orchestrattion_info.get("name", ""), node.get("module", "")
                )

        # 加载 “开始” 中的输出数据
        #  “开始” 节点列表
        start_node_list: list[dict] = list()
        for node in orchestrattion_info.get("nodes", []):
            if node.get("type", "") == "START":
                start_node_list.append(node)
                # 将module名称加入idl_list
                idl_list.append(node.get("module", ""))

        # end节点的列表
        end_node_list: List[dict] = list()
        for node in orchestrattion_info.get("nodes", []):
            if node.get("type", "") == "END":
                end_node_list.append(node)
                # 将module名称加入idl_list
                idl_list.append(node.get("module", ""))

        # 对于每个节点，找到它的上一个节点和下一个节点的列表

        pass